<template>

  <!-- 文件预览/上传弹框 -->
  <el-dialog title="文件列表" :visible.sync="previewFilesShow" width="60%" :before-close="setparentShow" append-to-body>
    <!-- 文件上传 -->
    <el-upload v-if="upload" :disabled="taskrowStatas>2" class="upload-demo" :show-file-list="false"
      :auto-upload="false" action="" :on-preview="onPreview" :before-remove="beforeRemove" :on-change="uploadOnchange"
      multiple :limit="5" :on-exceed="handleExceed" :file-list="fildData">
      <el-button size="small" :disabled="taskrowStatas>2" type="primary">点击上传</el-button>
      <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
    </el-upload>
    <z-table :list="fildData" class="current_page_classname" :tableProps="serviceTableProps" :columns="columns">
      <template v-slot:content="v">
        <span v-if="v.key == 'download'">
          <span @click.stop="download(v.row)" class="icon-class text-blue">
            <svg-icon icon-class="download" />
          </span>
        </span>
        <span v-else>{{ v.row[v.key] }}</span>
      </template>
      <template v-slot:operation="v" v-if="upload">
        <a style="margin-left:5px;" href="JavaScript:;" class="text-red"
          @click.prevent.stop="deletefild(v.row,v.$index)">删除</a>
      </template>
    </z-table>
    <span slot="footer" class="dialog-footer" v-if="upload">
      <el-button @click="setparentShow">取 消</el-button>
      <el-button type="primary" @click="submit" :loading="submitLoading">确 定</el-button>
    </span>
  </el-dialog>

</template>

<script>
import commonMixin from '@/views/_common/mixin'
export default {
  name: 'previewFiles',
  mixins: [commonMixin],
  components: {},
  props: {
    previewFilesShow: {
      type: Boolean,
      default: false,
    },
    upload: {
      type: Boolean,
      default: false,
    },
    taskrowStatas: {
      type: Number,
      default: 0,
    },
    fildData: {
      type: Array,
      default: function () {
        return []
      },
    },
    taskId: {
      type: String,
      default: '',
    },
    maintainShow: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      baseUrl: this.$api.baseUrl,
      serviceTableProps: {
        border: true,
        hideOperations: true,
      },
      columns: [
        { title: '文件Id', key: 'id', fixed: 'left' },
        { title: '文件名称', key: 'name' },
        { title: '文件地址', key: 'file_path' },
        { title: '修改人', key: 'modify_user', width: 100 },
        { title: '最后修改时间', key: 'modify_time', width: 100 },
        { title: '文件下载', key: 'download', width: 100 },
      ],
      submitLoading: false,
      fileList: [],
      formData: new FormData(),
      deleteArray: [],
    }
  },
  computed: {},
  watch: {
    upload: {
      immediate: true,
      handler(val, old) {
        if (val) {
          this.serviceTableProps = {
            border: true,
            opsColWith: 100,
            fixed: false,
            hideOperations: false,
          }
        }
      },
    },
  },
  created() {},
  mounted() {},
  methods: {
    deletefild(v, index) {
      if (v.id) {
        this.deleteArray.push(v.id)
        this.$parent.fildData.splice(index, 1)
      } else {
        let newArr = this.fildData.filter((x) => x.name != v.name)
        this.$parent.fildData = newArr
        this.formData = new FormData()
        // 刚上传没有点确定
        this.fildData.forEach((i) => {
          if (!i.id && i.name != v.name) {
            this.formData.append('files', i.raw)
          }
        })
      }
    },
    submit() {
      this.submitLoading = true
      let data = {
        id: this.taskId,
        deleteArray: this.deleteArray,
      }
      this.formData.append('model', JSON.stringify(data))
      let url = ''
      if (this.maintainShow) {
        url = this.baseUrl + 'Tpm/TpmMaintenanceTask/UploadMaintenanceTaskDetailFiles'
      } else {
        url = this.baseUrl + 'Tpm/TpmSpotCheckTask/UploadTaskDetailFiles'
      }
      this.$request(url, this.formData, 'post')
        .then((r) => {
          this.$message.success('操作成功')
          this.deleteArray = []
          this.setparentShow()
        })
        .finally(() => {
          this.submitLoading = false
          this.formData = new FormData()
        })
    },
    // 履历详情
    download(v) {
      this.filedownload(this.$api.baseUrl, v)
    },
    filedownload(host, file) {
      host = host.replace('api/', '')
      let a = document.createElement('a')
      a.setAttribute('href', this.fileUrl(host, file.file_path))
      a.setAttribute('target', '_blank')
      a.setAttribute('download', file.name)

      a.click()
      a.remove()
    },
    fileUrl(host, file) {
      host = host.replace('api/', '')
      return host + file
    },
    // 控制父级关闭弹框
    setparentShow() {
      this.$parent.previewFilesShow = false
    },
    // 上传
    uploadOnchange(file, fileList) {
      let f = file.raw
      const isLt20M = f.size / 1024 / 1024 < 20
      if (!isLt20M) {
        fileList.splice(fileList.indexOf(f), 1)
        return this.$message.error('上传档案大小不能超过 20MB!')
      }
      this.$parent.fildData.push(file)
      this.formData.append('files', f)
    },
    // 清除附件
    beforeRemove(file, fileList) {
      return this.$confirm(`确定要删除${file.name}?`, 提示, {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {
        if (file.id) {
          // 已经有附件了,进行删除
          this.deleteArray.push(file.id)
        } else {
          this.formData = new FormData()
          // 刚上传没有点确定
          fileList.forEach((i) => {
            if (!i.id && i.name != file.name) {
              this.formData.append('files', i.raw)
            }
          })
        }
      })
    },
    // 预览
    onPreview(file) {
      alert('没有接口看个毛')
    },
    // 超过最大上传数
    handleExceed() {
      return this.$message.warning('最多只能上传5张图片')
    },
  },
}
</script>

<style lang="scss" scoped>
.icon-class {
  font-size: 18px;
  cursor: pointer;
}
.current_page_classname ::v-deep .el-table__row {
  td:not(.is-hidden):last-child {
    right: -3px;
  }
}
::v-deep .el-table .el-table__cell.is-center {
  text-align: center;
  right: -3px;
}
</style>